<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Express extends Base_Controller{

	/**
	 * Index Page for this controller.
	 *
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	//获取物流信息

	public function getExpress()
	{
		$order_no=$this->input->post('order_no');
		$data = array(
			"OrderCode"=>$this->input->post('OrderCode'),//订单编号
			"ShipperCode"=>$this->input->post('ShipperCode'), //快递公司编码
			"LogisticCode" => $this->input->post('LogisticCode'),//物流单号
		);
		if($data['OrderCode'] == '' || $data['ShipperCode'] == ''|| $data['LogisticCode'] == '') die($this->responseApi(false,'您没有传入物流参数！'));

		$CustomerName = '';
		if($data['ShipperCode']=='SF')
		{
			$uid=$this->db->get_where('mall_order', array('order_no' => $order_no))->row_array()['user_id'];
			//购买人手机号后四位 $CustomerName
			$CustomerName=$this -> db ->get_where('mall_user', array('id' => $uid))->row_array()['username'];
			if(empty($CustomerName)) die($this->responseApi(false,'用户不存在！'));
		}
		$logisticResult=$this->getOrderTracesByJson($data['OrderCode'] , $data['ShipperCode'],$data['LogisticCode'],$CustomerName);
		//存储物流信息
		$logistic=$this->db->get_where('mall_logistic', array('order_no' => $order_no))->row_array();
		if($logistic)
		{
			$this->db->where(['order_no'=>$logistic['order_no']]) -> update('mall_logistic', ['back_data'=>$logisticResult]);
		}
		else
		{
			$this->db->insert('mall_logistic', ['order_no'=>$order_no,'order_number'=>$data['OrderCode'],'shipper_code'=>$data['ShipperCode'],'logistic_code'=>$data['LogisticCode'],'back_data'=>$logisticResult]);
		}
		echo $logisticResult;
	}
	/**
	 * Json方式 查询订单物流轨迹
	 */


	public function getOrderTracesByJson($OrderCode , $ShipperCode,$LogisticCode,$CustomerName){
		if($CustomerName != ''){
			$requestData= "{'OrderCode':'".$OrderCode."','ShipperCode':'".$ShipperCode."','LogisticCode':'".$LogisticCode."'}";
		}else{
			$requestData= "{'OrderCode':'".$OrderCode."','ShipperCode':'".$ShipperCode."','LogisticCode':'".$LogisticCode."','CustomerName':'".$CustomerName."'}";
		}
		$kdn_config=$this->db->query("select * from admin_setting where group_key='kd_kdn'")->result_array();

		$datas = array(
			'EBusinessID' => $kdn_config[0]['EBusinessID'],
			'RequestType' => '8001',
			'RequestData' => urlencode($requestData) ,
			'DataType' => '2',
		);
		$datas['DataSign'] = $this->encrypt($requestData, $kdn_config[0]['AppKey']);

		$result=$this->sendPost($kdn_config[0]['ReqURL'], $datas);

		//根据公司业务处理返回的信息......

		return $result;
	}

	/**
	 *  post提交数据
	 * @param  string $url 请求Url
	 * @param  array $datas 提交的数据
	 * @return url响应返回的html
	 */
	public function sendPost($url, $datas) {
		$temps = array();
		foreach ($datas as $key => $value) {
			$temps[] = sprintf('%s=%s', $key, $value);
		}
		$post_data = implode('&', $temps);
		$url_info = parse_url($url);
		if(empty($url_info['port']))
		{
			$url_info['port']=80;
		}
		$httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
		$httpheader.= "Host:" . $url_info['host'] . "\r\n";
		$httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
		$httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
		$httpheader.= "Connection:close\r\n\r\n";
		$httpheader.= $post_data;
		$fd = fsockopen($url_info['host'], $url_info['port']);
		fwrite($fd, $httpheader);
		$gets = "";
		$headerFlag = true;
		while (!feof($fd)) {
			if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
				break;
			}
		}
		while (!feof($fd)) {
			$gets.= fread($fd, 128);
		}
		fclose($fd);

		return $gets;
	}

	/**
	 * 电商Sign签名生成
	 * @param data 内容
	 * @param appkey Appkey
	 * @return DataSign签名
	 */
	public function encrypt($data, $appkey) {
		return urlencode(base64_encode(md5($data.$appkey)));
	}
}
